﻿//写cookies
function setCookie(name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30 * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) +
    ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(name + "=");
        if (c_start != -1) {
            c_start = c_start + name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            var a = unescape(document.cookie.substring(c_start, c_end));
            return a;
        }
    }
    return "";
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

function toLogin() {
    //decodeURIComponent
    window.location.href = "/Home/Login?fromurl=" + encodeURIComponent(window.location.href);
}

function setPageSize() {
    setCookie("pk_pageSize", $("#pk_pageSize").val());
}
function getPageSize() {
    return getCookie("pk_pageSize");
}
//分页控件
$.fn.Pager = function (option) {
    var data = option.data;
    var pageSize = getPageSize();
    if (data.TotalPageCount == 0) return;
    var btnCount = option.btnCount || 5;    //按钮数量
    $(this).addClass("pager");
    btnCount = data.TotalPageCount > btnCount ? btnCount : data.TotalPageCount;
    var currIndex = data.CurrentPageIndex;  //当前页  从1开始
    var tmp = parseInt(btnCount / 2);
    $(this).empty();
    $(this).append("<div style='float:left'>当前：" + currIndex + "/" + data.TotalPageCount + "页&nbsp;&nbsp;&nbsp;共计：" + data.TotalItemCount + "项</div>");
    $(this).append('<select name="pageSize" id="pk_pageSize" style="margin-left: 10px;float: left;height: 30px;margin-top: -2px;" onchange="setPageSize();' + option.methodStr + '(1,\'' + option.args + '\')">' +
        '<option value="10" ' + (pageSize == 10 ? "selected" : "") + '>每页10行</option>' +
        '<option value="30" ' + (pageSize == 30 ? "selected" : "") + '>每页30行</option>' +
        '<option value="50" ' + (pageSize == 50 ? "selected" : "") + '>每页50行</option>' +
        '<option value="100" ' + (pageSize == 100 ? "selected" : "") + '>每页100行</option>' +
        '<option value="200" ' + (pageSize == 200 ? "selected" : "") + '>每页200行</option></select>');
    $(this).append("<a class='pager_btn' onclick='" + option.methodStr + "(1,\"" + option.args + "\")'>首页</a>");
    var classStr;
    var star = currIndex - tmp <= 0 ? 1 : currIndex - tmp;
    for (var i = star; i <= (star + btnCount) ; i++) {
        if (i <= 0 || i > data.TotalPageCount) continue;
        classStr = i == currIndex ? "on" : "";
        $(this).append("<a class='" + classStr + "'  onclick='" + option.methodStr + "(" + i + ",\"" + option.args + "\")'>" + i + "</a>");
    }
    $(this).append("<a class='pager_btn'  onclick='" + option.methodStr + "(" + data.TotalPageCount + ",\"" + option.args + "\")'>末页</a>");


}


//调用 $("#xxx").SetHtmlData(data, key);
$.fn.SetHtmlData = function (data, key) { SetHtmlData(data, $(this), key); };
//data 为json.Attr或者任意JSON格式
//obj 为容器对象 所有拼接的HTML都将放入这个容器中
//HTML中 字段用 {字段名} 来占位。字段名与JSON中一致，则会自动替换。
//容器中 放置一个 class="copyitem" 的隐藏层，用于存放原始HTML
function SetHtmlData(data, obj, key) {
    //原始HTML，用于替换的隐藏HTML
    var initHtml = $(".copyitem", obj).html().replace("fordel", "delete");
    var len = data.length;
    var index = 0;
    if (len > 0) {
        for (var i = 0; i < len; i++) {
            index = index + 1;
            var model = data[i];
            obj.append(_SetHtmlDataAction(model, initHtml, key, index));
        }
    } else {
        obj.append(_SetHtmlDataAction(data, initHtml, key));
    }
    //参考HTML   
    //<ul id="order_lastbuy" class="checklist orderinfo">
    //    <div id="forLiCopy" class="copyitem" style="display: none">
    //        <li class="fordel" data-id="{guid}">{name}</li>
    //    </div>
    //</ul>
}
function _SetHtmlDataAction(data, html, key, index) {
    var colArr = Object.keys(data);
    for (var j = 0; j < colArr.length; j++) {
        var colName = colArr[j];
        var seed = key == colName ? ("_" + (new Date()).valueOf()) : "";
        var rex = new RegExp("{" + colName + "}", 'g');
        //var valValue = data[colName];
        //if (colName == "PaiDuiTime") {
        //    if (data[colName] == null) {
        //        valValue = "";
        //    } else {
        //        valValue = data[colName].toString().replace("T00:00:00", "");
        //    }

        //}
        html = html.replace(rex, data[colName] + seed);
        html = html.replace(/{index}/g, index); //序号  关键字为 {index}
    }
    html = html.replace("{data-obj}", escape(JSON.stringify(data)));
    html = html.replace("T00:00:00", "");
    html = html.replace("null", "");
    return html;
}



$.fn.ajaxc = function (url, dataMap, fnSuccess, fnErr) {
    var $obj = $(this);
    if (url) {
        msgload(0, "正在玩命加载");
        // $obj.html('<div class="loading-style1 " style="width: 100%;"><b></b></div>');
        $.ajaxc(url, dataMap, fnSuccess, fnErr);
    } else {
        msgload(0, "正在玩命加载");
        //没有URL链接，则只显示LOAD动画
        //  $obj.html('<div class="loading-style1 " style="width: 100%;"><b></b></div>');
    }
};

function ajaxcCns(url, dataMap, fnSuccess, fnErr) {
    $.ajax({
        type: "POST",
        url: url,
        data: dataMap,
        dataType: "json",
        success: function (data) {
            msgloadclose();
            if (ajaxDone(data)) {
                fnSuccess(data);
            } else {

                if (data.message == '登录超时，请重新登录！') {
                    location.href = '/Me/Login';
                } else {
                    if (fnErr) fnErr(data);
                }
            }
        },
        error: function (data) {
            data.message = data.message || "保存失败！";
            if (data.message == '登录超时，请重新登录！') {
                location.href = '/Me/Login';
            } else {
                if (fnErr) fnErr(data);
            }
        }
    });
}

$.ajaxc = function (url, dataMap, fnSuccess, fnErr) {
    $.ajax({
        type: "POST",
        url: url,
        data: dataMap,
        dataType: "json",
        success: function (data) {
            msgloadclose();
            if (ajaxDone(data)) {
                fnSuccess(data);
            } else {
                
                if (data.message == '登录超时，请重新登录！') {
                    location.href = '/Me/Login';
                } else {
                    if (fnErr) fnErr(data);
                }
            }
        },
        error: function (data) {
            data.message = data.message || "保存失败！";
            if (data.message == '登录超时，请重新登录！') {
                location.href = '/Me/Login';
            } else {
                if (fnErr) fnErr(data);
            }
        }
    });
};

$.fn.Loader = function (fn, time) {
    var html = '<div class="stage-5-icon"><div class="stage-5-icon-cover"></div><div class="stage-5-icon-mask"></div><div class="stage-5-icon-front"><div class="stage-5-icon-gear stage-5-icon-gear-1  loading-right"></div><div class="stage-5-icon-gear stage-5-icon-gear-2  loading-left"></div><div class="stage-5-icon-gear stage-5-icon-gear-3  loading-left"></div></div><div class="stage-5-icon-back"><div class="stage-5-icon-gear stage-5-icon-gear-4 loading-right"></div><div class="stage-5-icon-gear stage-5-icon-gear-5 loading-right"></div><div class="stage-5-icon-gear stage-5-icon-gear-6 loading-left"></div></div></div>';
    $(this).html(html);
    var $obj = $(this);
    setTimeout(function () {
        $(".stage-5-icon-back", $obj).css({ "background": "#202227" });
    }, 100);

    $(".stage-5-icon-cover", $obj).animate({ "margin-left": 170 }, "slow");
    LoadRotation();
    if (time) {
        setTimeout(function () {
            if (fn) fn();
        }, time);
    }
};


var LoadRotation = function () {
    var time = 360;
    var duration = 5000;
    $(".loading-right").rotate({
        angle: 0,
        animateTo: time,
        duration: duration,
        callback: LoadRotation,
        easing: function (x, t, b, c, d) { // t: current time, b: begInnIng value, c: change In value, d: duration
            return c * (t / d) + b;
        }
    });
    $(".loading-left").rotate({
        angle: 0,
        animateTo: -time,
        duration: duration,
        callback: LoadRotation,
        easing: function (x, t, b, c, d) { // t: current time, b: begInnIng value, c: change In value, d: duration
            return c * (t / d) + b;
        }
    });
};



$.fn.ajaxLoad = function (url, fnSuccess, fnErr) {
    $.ajaxLoad(url, $(this), fnSuccess, fnErr);
};

$.ajaxLoad = function (url, obj, fnSuccess, fnErr) {
    var $con = $("#forajaxload");
    if ($con.length == 0) {
        $("body").append("<div  id='forajaxload' style='display:none'></div>");
        $con = $("#forajaxload");
    }
    $(obj).Loader();
    $con.load(url, function (data) {
        $con.empty();
        if (ajaxDone(data)) {
            $(obj).html(data);
            if (fnSuccess) fnSuccess();
        }
    });

};

function ajaxDone(data, isHide) {
    var flag = true;
    try {
        var jsonData = typeof (data) == "string" ? $.parseJSON(htmlDecode(data)) : data;
        switch (jsonData.statusCode.toString()) {
            case "301":
                flag = false;
                //msginfo(jsonData.message);
                LoginDialog();
                break;
            case "300":
                flag = false;
                if (!isHide) msgerr(jsonData.message);
                break;
            default:
                flag = true;
                break;
        }
    } catch (e) {

    }
    return flag;
}


//FORM表单提交，  form对象，option参数
$.fn.PostForm = function (option) {
    PostForm($(this), option);
};

//FORM提交
function PostForm(form, option) {
    var flag = true;
    if (option.vfn) {
        flag = option.vfn();
    }
    if (flag) {
        var $form = $(form);
        $.ajax({
            type: $form.method || 'POST',
            url: $form.attr("action"),
            data: $form.serializeArray(),
            dataType: "json",
            cache: false,
            success: function (data) {
                if (ajaxDone(data)) {
                    option.success(data);
                } else {
                    option.error(data);
                }
            },
            error: function (data, status, xhr) {
                data.message = status || "保存失败！";
                if (option.error) option.error(data);
                else msgerr(data);
            },
            complete: function () {
                if (option.complete) option.complete();
            }
        });
    }
}

function msginfo(arg) {
    var option = {};
    if (typeof (arg) == "string") {
        option.message = arg;
        option.mask = 1;
    } else {
        option = arg;
    }
    option.id = option.id || "showDown_info";
    option.title = (option.title || "提示");
    option.type = "info";
    msg(option);
}

function msgcon(arg) {
    var option = {};
    if (typeof (arg) == "string") {
        option.message = arg;
    } else {
        option = arg;
    }
    option.id = option.id || "showDown_con";
    option.title = (option.title || "温馨提示");
    option.mask = option.mask || 1;
    option.type = "con";
    msg(option);
}

function msgerr(arg) {
    var option = {};
    if (typeof (arg) == "string") {
        option.message = arg;
        option.mask = 1;
    } else {
        option = arg;
    }
    option.id = option.id || "showDown_err";
    option.title = (option.title || "错误");
    option.type = "err";
    //option.autoClose = option.autoClose || 3000;
    //option.hideBtn = option.hideBtn || 0;
    msg(option);
}

function msgsuc(arg) {
    var option = {};
    if (typeof (arg) == "string") {
        option.message = arg;
        option.mask = 1;
    } else {
        option = arg;
    }
    option.id = option.id || "showDown_suc";
    option.title = (option.title || "成功");
    option.type = "suc";
    //option.autoClose = option.autoClose || 3000;
    //option.hideBtn = option.hideBtn || 0;
    msg(option);
}


function LoginDialog(errMsg, userid, userpwd) {
    userid = userid || "";
    userpwd = userpwd || "";
    msg({
        id: "logindialog",
        title: "会员登录",
        yesTxt: "登录",
        yesFn: function () {
            userid = $("#loginformDialogUserId").val();
            userpwd = $("#loginformDialogPwd").val();
            var isok = true;
            $("#loginformDialog input").each(function () {
                if ($(this).val() == "") {
                    LoginDialog($(this).attr("placeholder"), userid, userpwd);
                    isok = false;
                    return isok;
                }
            });
            if (!isok) return isok;
            var $form = $("#loginformDialog");
            $.ajax({
                type: $form.method || 'POST',
                url: $form.attr("action"),
                data: $form.serializeArray(),
                dataType: "json",
                cache: false,
                success: function (data) {
                    if (ajaxDone(data, true)) {
                        location.reload();
                    } else {
                        LoginDialog(data.message, userid, userpwd);
                    }
                },
                error: function (data) {
                    data.message = data.message || "服务器繁忙，请稍后再试";
                    LoginDialog(data.message, userid, userpwd);
                }
            });
        },
        noTxt: "关闭",
        noFn: function () { },
        message: "<form id='loginformDialog'  action='/Home/Login' method='post'><ul>" +
            "<li><span>会员名</span><input type='text' id='loginformDialogUserId' name='UserId' value='" + userid + "' placeholder='请填入您的会员名'/> </li>" +
            "<li><span>密码</span><input type='password'  id='loginformDialogPwd' name='Pwd' value='" + userpwd + "'  placeholder='请填入您的登录密码'/> </li>" +
            "<li><span>验证码</span><input type='text'  id='loginformDialogCode' name='Code' placeholder='请填入右侧的验证码'/>" +
            " <img style='margin-left: -85px;cursor: pointer; vertical-align: middle' src='/Home/VerifyImage' id='VerifyImage' title='看不清？点击换一个' onclick='javascript:document.getElementById(\"VerifyImage\").src =\"/Home/VerifyImage?r=\"+Math.random();return false;'></li>" +


          (errMsg ? ("<li class='error'>" + errMsg + "</li>") : "") +
            "</ul></form>"

    });
}

function msgload(time, msg) {
    $("#loadingToast .weui_toast_content").html(msg || "数据加载中");
    $('#loadingToast').show();
    time = time == 0 ? 999999 : 2000;
    setTimeout(function () {
        $('#loadingToast').hide();
    }, time);
}

function msgloadclose() {
    $('#loadingToast').hide();
}

function msgclose(id) {
    $("#" + id).remove();
}

function msg(option) {
    var id = (option.id || new Date().getTime());   //自定义ID
    var containerId = "dialog_" + id; //容器ID
    if ($("#" + containerId).length > 0) $("#" + containerId).remove();

    var title = option.title || "";
    var html = option.message || (option.msg || "");
    var widthStr = option.width ? ("width:" + option.width + "px") : "";
    //用于动态加载网页内容  先保留，后期扩展
    var url = option.url || "";
    //弹框类型
    var type = option.type || "info";
    var htmlclass = "weui_dialog_alert";
    if (type == "con") {
        htmlclass = "weui_dialog_confirm";
    }

    //只有等于false的时候才不显示遮罩层
    var mask = option.mask != false ? true : false;
    var htmlmask = '';
    if (mask) {
        htmlmask = '<div class="weui_mask"></div>';
    }




    //绑定时间及按钮文本
    var btnyes = option.yesTxt || "确定";
    var btnno = option.noTxt || "";
    var yesFn = option.yesFn || null;
    var noFn = option.noFn || null;
    //默认只有一个YES 按钮
    var htmlyes = '<a href="javascript:;" class="weui_btn_dialog_yes primary">' + btnyes + '</a>';
    var htmlno = '';
    //如果有NO 按钮 回调事件 则显示NO 按钮
    if (noFn) {
        htmlno = '<a href="javascript:;" class="weui_btn_dialog_no primary">' + btnno + '</a>';
    }

    if (url) {
        html = "页面加载中，请稍后...";
    }


    var msghtml = '<div class="' + htmlclass + '" id="' + containerId + '" style="display: none;">' +
        htmlmask +
        '<div class="weui_dialog" style="' + widthStr + '">' +
        '<div class="weui_dialog_hd"><strong class="weui_dialog_title">' + title + '</strong></div>' +
        '<div class="weui_dialog_bd" >' + html + '</div>' +
        '<div class="weui_dialog_ft">' +
        htmlno +
        htmlyes +
        '</div>' +
        '</div>' +
        '</div>';

    $("body").append(msghtml);
    
    if (url) {
        $("#" + containerId + " .weui_dialog_bd").load(url, function (data, status, xhr) {
            if (status == "success") {
                if (!ajaxDone(data)) {
                    //页面异常
                    msgclose(id);
                }
            } else {
                //请求失败
                msgclose(id);
                msgerr({ message: xhr.status + " " + xhr.statusText });
            }
            //DialogLoading({ id: id }, false);
        });
    }




    var $dialog = $('#' + containerId);
    $dialog.show();
    if (yesFn) {
        $dialog.find('.weui_btn_dialog_yes').one('click', function () {
            $dialog.hide();
            yesFn();
        });

    } else {
        $dialog.find('.weui_btn_dialog_yes').one('click', function () {
            $dialog.hide();
        });
    }
    if (noFn) {
        $dialog.find('.weui_btn_dialog_no').one('click', function () {
            $dialog.hide();
            noFn();
        });

    } else {
        $dialog.find('.weui_btn_dialog_no').one('click', function () {
            $dialog.hide();
        });
    }
}

//html代码转异
function htmlDecode(str) {
    str = str.replace(/&amp;/gi, "&");
    str = str.replace(/&nbsp;/gi, " ");
    str = str.replace(/&quot;/gi, "\"");
    str = str.replace(/&#39;/g, "'");
    str = str.replace(/&lt;/gi, "<");
    str = str.replace(/&gt;/gi, ">");
    //     str = str.replace(/<br[^>]*>(?:(rn)|r|n)?/gi, "n");
    return str;
}


function loger(obj) {
    console.log(obj);
}
var browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核 
            presto: u.indexOf('Presto') > -1, //opera内核 
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 
            mobile: !!u.match(/AppleWebKit.*Mobile/) || !!u.match(/Windows Phone/) || !!u.match(/Android/) || !!u.match(/MQQBrowser/), //是否为移动终端 
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器 
            iPad: u.indexOf('iPad') > -1, //是否iPad 
            iosApp: u.indexOf('xquios') > -1,
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部 
        };
    }()
};

